// components/assistIpt/assistIpt.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    accountId: {
      observer(val){
        this.setAssistAccount(val);
      }
    },

    valid:{
      type: Boolean,
      value: false
    },

    defData: {
      type: Object,
      observer(val){
        if (!val){
          this.setData({
            defValue: {}
          })
          return
        }
        let {id,name,type} = val,
          {fieldList} = this.data,
          ids = id && id.split(','),
          names = name && name.split(','),
          obj = {};
        wx.$each(fieldList,(i,item)=>{
          obj[ 'json_' + i] = ids[i]
        })
        this.setData({
          defValue: obj
        })
      }
    },

    tableType: {

    },
    entityParam:{},
    disabled:{}
  },

  /**
   * 组件的初始数据
   */
  data: {
    accountList: {},  //科目列表
    fieldList: [],  //核算项目字段
    optionsList: {},   //核算项目选项

    defValue: {},
    // validObj:{}

    isEdit: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //字段修改
    bindChange(e){
      let {field,val} = e.detail,
        index = field.field_id.split('_')[1], //辅助核算类型数组索引
        item = field.optionList.find(ite=>{
          return ite.row_id == val
        }),
        name = item && item[field.optionName];
      this.data.assistIdArr[index] = val;
      this.data.assistNameArr[index] = val ? val + ' ' + name : '';

      this.triggerEvent('change',{
        type: this.data.assistTypeArr,
        id: this.data.assistIdArr,
        name: this.data.assistNameArr,
      })
    },

    //获取辅助核算
    getAssistAccount(){
      return new Promise(resolve => {
        if (this.data.assistList) {
          resolve({assist:this.data.assistList});
          return
        }
        wx.$post(1,'AllAssistAccount/select_all_assist_account',{}).then(res=>{
          if (res.errcode != 0)return;
          this.setData({
            assistList: res.data.row || []
          });
          resolve({assist:res.data.row || []});
        })
      })
    },
    //获取科目信息
    getAccount(id){
      return new Promise(resolve => {
        let {accountList} = this.data;
        if (accountList && this.data.accountList[id]) {
          resolve({account:this.data.accountList[id]});
          return
        }
        let post = {"page":1,"limit":0,"oby":"account_id","SearchWhere":[]};
        if (typeof id === 'object'){
          id.forEach(item=>{
            post.SearchWhere.push({"CompareWith":"account_id","Operator":"=","CompareValue":item,"or":1})
          })
        }else {
          post.SearchWhere.push({"CompareWith":"account_id","Operator":"=","CompareValue":id,"or":1})
        }
        wx.$post(3,'Account/query_account',post).then(res=>{
          if (res.errcode != 0)return;
          let data = res.data.row || [],
            assist = [];
          data.forEach(item=>{
            let assistJson = item.assist_account_json,
              assistArr = [];
            assistJson && (assistArr = assistJson.split(','));
            assistArr.forEach(ite=>{
              assist.indexOf(ite) < 0 && assist.push(ite);
            });
            accountList[item.account_id] = item;
          });

          this.setData({accountList});
          resolve({assistType: assist});
        })
      })
    },
    //获取核算项目选项
    getOptionList(tid){
      let post = {"oby": tid + ".row_id desc","table_id": tid,"page":1,"limit":0};
      return new Promise(resolve => {
        if (this.data.optionsList[tid]){
          resolve(this.data.optionList[tid]);
          return
        }
        wx.$post(3,'DynamicQuery/query_dynamic_v3',post).then(res=>{
          if (res.errcode !=0)return;
          resolve(res.data.row || []);
        })
      })
    },

    //获取模块设置会计凭证参数
    getEntityVoucher(){
      let {tableid} = this.data,
        url = 'Voucher/query_all_voucher_template',
        post = {"page":1,"limit":0,"table_id":tableid},
        accountList = [];
      return new Promise(resolve => {
        wx.$post(3,url,post).then(res=>{
          if (res.errcode != 0)return;
          let data = res.data.row || [];
          data.forEach(item=>{
            let accountid = item.account_id;
            accountid && accountList.indexOf(accountid)<0 && accountList.push(accountid);
          });
          resolve(accountList);
        })
      })
    },

    //设置辅助核算项目
    setAssistAccount(account){
      Promise.all([this.getAssistAccount(),this.getAccount(account)]).then(res=>{
        let data = {...res[0],...res[1]};
        // let assistType = data.account && data.account.assist_account_json,
        let
          // assistName = data.account.assist_account_value,
          // assistTypeArr = assistType && assistType.split(','),
          assistTypeArr = data.assistType,
          // assistNameArr = assistName && assistName.split(','),
          fieldList = [],
          tables = [],
          defArr = [],
          defValue = {};
        if (this.data.defData){
          let {id,name} = this.data.defData,
            ids = id && id.split(','),
            names = name && name.split(',');
          wx.$each(ids,(i,item)=>{
            defArr.push({id: item,name: names[i]});
          });
        }
        wx.$each(data.assist,(i,item)=>{
          let id = item.row_id.toString();
          if (assistTypeArr && assistTypeArr.indexOf(id)>=0){
            let index = fieldList.length,
              id = 'json_' + index;
            fieldList.push({
              field_id: id,
              // label: assistNameArr[i],
              label: item.assist_account,
              type: 'picklist',
              is_null: false,
              optionList: [],
              optionId: 'row_id',
              optionName: item.field_id,
            });
            defArr[index] && (defValue[id] = defArr[index].id);
            tables.push(this.getOptionList(item.table_id))
          }
        });
        Promise.all(tables).then(res=>{
          wx.$each(fieldList,(i,item)=>{
            item.optionList = res[i];
          });
          this.setData({fieldList,assistTypeArr,assistIdArr: [],assistNameArr: [],isEdit: true});

          this.setData({defValue});
          this.setData({isEdit: false});
        })
      })
    }
  },

  ready(){
    let {tableType,entityParam} = this.data;

    if (tableType === '自定义借' || tableType === '自定义贷'  //明细表自定义借贷
      || (entityParam && [1,2,3,'1','2','3'].includes(entityParam.detailed_voucher_type)) // 主表模块参数：多借多贷、一借多贷、一贷多借类型
    ) {
      return
    }
    this.getEntityVoucher().then(account=>{
      this.setAssistAccount(account);
    });
  }
})
